package com.mic.yzzn.plc.common.instructions.request;

import com.mic.yzzn.plc.common.ins.datastructure.PLCWordContacotNumber;
import com.mic.yzzn.plc.common.instructions.basic.PLCRequestInstruction;
import org.apache.commons.lang.StringUtils;

/**
 * Created by ASH on 16/4/11.
 */
public class PLCWordContactorReadInstruction extends PLCWordContactorInstruction
{
    /**
     * 初始化方法
     */
    public PLCWordContactorReadInstruction()
    {
        new PLCDataRegisterInstruction();

        requestCode = PLCRequestInstruction.READ_WORD_UNIT_CONTACTOR_INS;
    }

    /**
     * 用字符串初始化
     */
    @Override
    public String initWithString(String instructionString) throws IllegalArgumentException
    {
        String tempResult = super.initWithString(instructionString);

        // 判断请求码与当前指令的请求码是否符合
        int requestCodeLength = requestCode.length();
        if (!(StringUtils.substring(tempResult, 0, requestCodeLength).equals(requestCode)))
        {

            throw new IllegalArgumentException("PLCSingleContactorReadInstruction's requestCode must be \"" + requestCode + "\"");
        }

        // 截取请求码
        tempResult = StringUtils.substringAfter(tempResult, requestCode);

        // 获取触点代码
        String contactorCode = tempResult.substring(0, 1);
        this.contactorCode = contactorCode;

        // 截断数据代码
        tempResult = StringUtils.substringAfter(tempResult, contactorCode);

        // 判断数据范围是否正确
        if (tempResult.length() < 8)
        {
            throw new IllegalArgumentException("the length PLCDataRegisterNumber's beginNumber and endNumber must be 4");
        }

        // 设置数据范围
        this.wordContacotNumber = new PLCWordContacotNumber(tempResult.substring(0, 4), tempResult.substring(4, 8));

        // 截断数据范围
        tempResult = StringUtils.substringAfter(tempResult, contactorCode.toString());

        return tempResult;
    }
}
